import { useState, useEffect } from "react";
import { Form, Input, Button, Checkbox, Switch, message } from "antd";
import type { FormProps } from "antd";
import { useNavigate } from "react-router-dom";
import {
  UserOutlined,
  LockOutlined,
  InfoCircleOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  MobileOutlined,
  QrcodeOutlined,
  UserAddOutlined,
  WechatOutlined,
  WeiboOutlined,
  AlipayOutlined,
  GlobalOutlined,
  BulbOutlined,
  BulbFilled,
  ReloadOutlined,
} from "@ant-design/icons";
import { useAppDispatch, useAppSelector } from "../../store/hooks";
import { toggleTheme } from "../../store/slices/themeSlice";
import { loginAsync, clearError } from "../../store/slices/userSlice";
import styles from "./Login.module.scss";

interface LoginFormValues {
  username: string;
  password: string;
  captcha: string;
  remember: boolean;
}

const Login = () => {
  const [form] = Form.useForm();
  const [captcha, setCaptcha] = useState("9024");
  const [loading, setLoading] = useState(false);
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const theme = useAppSelector((state) => state.theme.mode);
  const {
    isAuthenticated,
    error,
    loading: loginLoading,
  } = useAppSelector((state) => state.user);

  // 如果已登录，跳转到首页
  useEffect(() => {
    if (isAuthenticated) {
      navigate("/");
    }
  }, [isAuthenticated, navigate]);

  // 显示错误信息
  useEffect(() => {
    if (error) {
      message.error(error);
      dispatch(clearError());
    }
  }, [error, dispatch]);

  const generateCaptcha = () => {
    const newCaptcha = Math.floor(1000 + Math.random() * 9000).toString();
    setCaptcha(newCaptcha);
  };

  const onFinish: FormProps<LoginFormValues>["onFinish"] = async (values) => {
    try {
      setLoading(true);
      // 验证验证码（这里简化处理，实际应该与后端验证）
      if (values.captcha !== captcha) {
        message.error("验证码错误");
        generateCaptcha();
        form.setFieldsValue({ captcha: "" });
        setLoading(false);
        return;
      }

      // 调用登录接口
      const result = await dispatch(
        loginAsync({
          username: values.username,
          password: values.password,
          captcha: values.captcha,
        })
      ).unwrap();

      // 登录成功
      message.success("登录成功");

      // 如果选择了"7天内免登录"，可以在这里处理 token 的存储策略
      if (values.remember) {
        // 可以设置更长的 token 过期时间或使用 refresh token
        console.log("已选择7天内免登录");
      }

      // 跳转到首页
      navigate("/");
    } catch (err: any) {
      // 错误已在 Redux 中处理，这里只需要重新生成验证码
      generateCaptcha();
      form.setFieldsValue({ captcha: "" });
    } finally {
      setLoading(false);
    }
  };

  const handleThemeToggle = () => {
    dispatch(toggleTheme());
  };

  return (
    <div
      className={`${styles.loginContainer} ${
        theme === "dark" ? styles.darkTheme : styles.lightTheme
      }`}
    >
      {/* 右上角控制栏 */}
      <div className={styles.loginHeaderControls}>
        <Switch
          checked={theme === "dark"}
          onChange={handleThemeToggle}
          checkedChildren={<BulbFilled />}
          unCheckedChildren={<BulbOutlined />}
        />
        <Button
          type="text"
          icon={<GlobalOutlined />}
          className={styles.langBtn}
        >
          文A
        </Button>
      </div>

      <div className={styles.loginContent}>
        {/* 左侧插画区域 */}
        <div className={styles.loginLeft}>
          <div className={styles.loginIllustration}>
            <div className={styles.blueShape}></div>
            <div className={styles.illustrationFigure}>
              <div className={`${styles.floatingUiCard} ${styles.card1}`}>
                <div className={styles.cardMenu}></div>
                <div className={styles.cardDots}></div>
              </div>
              <div className={`${styles.floatingUiCard} ${styles.card2}`}>
                <div className={styles.cardMenu}></div>
                <div className={styles.cardRedDot}></div>
              </div>
              <div className={`${styles.floatingUiCard} ${styles.card3}`}>
                <div className={styles.cardMenu}></div>
                <div className={styles.cardPlus}></div>
              </div>
              <div className={styles.whiteFeather}></div>
            </div>
          </div>
        </div>

        {/* 右侧登录表单 */}
        <div className={styles.loginRight}>
          <div className={styles.loginFormWrapper}>
            {/* Logo 和标题 */}
            <div className={styles.loginLogo}>
              <div className={styles.logoIcon}>💧</div>
              <h1 className={styles.loginTitle}>PUREADMIN</h1>
            </div>

            {/* 登录表单 */}
            <Form
              form={form}
              name="login"
              onFinish={onFinish}
              layout="vertical"
              size="large"
              className={styles.loginForm}
              initialValues={{
                username: "admin",
                remember: false,
              }}
            >
              <Form.Item
                name="username"
                rules={[{ required: true, message: "请输入用户名" }]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="admin"
                  className={styles.loginInput}
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请输入密码"
                  iconRender={(visible) =>
                    visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
                  }
                  className={styles.loginInput}
                />
              </Form.Item>

              <Form.Item
                name="captcha"
                rules={[{ required: true, message: "请输入验证码" }]}
                className={styles.captchaFormItem}
              >
                <Input
                  prefix={<InfoCircleOutlined />}
                  placeholder="验证码"
                  className={styles.loginInput}
                  suffix={
                    <div
                      className={styles.captchaContainer}
                      onClick={generateCaptcha}
                    >
                      <span className={styles.captchaCode}>{captcha}</span>
                      <Button
                        type="link"
                        onClick={(e) => {
                          e.stopPropagation();
                          generateCaptcha();
                        }}
                        className={styles.captchaRefresh}
                        icon={<ReloadOutlined />}
                      />
                    </div>
                  }
                />
              </Form.Item>

              <div className={styles.loginOptions}>
                <Form.Item name="remember" valuePropName="checked" noStyle>
                  <Checkbox>
                    <InfoCircleOutlined style={{ marginRight: 4 }} />
                    7天内免登录
                  </Checkbox>
                </Form.Item>
                <a href="#" className={styles.forgotPassword}>
                  忘记密码?
                </a>
              </div>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  block
                  className={styles.loginButton}
                  loading={loading || loginLoading}
                >
                  登录
                </Button>
              </Form.Item>

              <div className={styles.loginAlternatives}>
                <Button block className={styles.altLoginBtn}>
                  <MobileOutlined /> 手机登录
                </Button>
                <Button block className={styles.altLoginBtn}>
                  <QrcodeOutlined /> 二维码登录
                </Button>
                <Button block className={styles.altLoginBtn}>
                  <UserAddOutlined /> 注册
                </Button>
              </div>

              <div className={styles.thirdPartyLogin}>
                <div className={styles.divider}>
                  <span>第三方登录</span>
                </div>
                <div className={styles.socialIcons}>
                  <Button
                    type="text"
                    icon={<WechatOutlined />}
                    className={styles.socialIcon}
                  />
                  <Button
                    type="text"
                    icon={<WeiboOutlined />}
                    className={styles.socialIcon}
                  />
                  <Button
                    type="text"
                    icon={<AlipayOutlined />}
                    className={styles.socialIcon}
                  />
                </div>
              </div>
            </Form>
          </div>

          {/* 版权信息 */}
          <div className={styles.loginFooter}>
            <span>Copyright © 2020-2025 PureAdmin</span>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
